/*
 *    Copyright (c) 2018-2025, madp All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: 成都文思海辉金信软件有限公司
 */
package com.pactera.madp.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.entity.SysFile;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.admin.config.FileUploadConfig;
import com.pactera.madp.admin.mapper.SysFileMapper;
import com.pactera.madp.admin.service.SysFileService;
import com.pactera.madp.common.core.constant.CommonConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.minio.service.MinioTemplate;
import com.pactera.madp.common.security.service.MadpUser;
import com.pactera.madp.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {
	private final MinioTemplate minioTemplate;
	private final FileUploadConfig fileUploadConfig;

	/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 */
	@Override
	public R uploadFile(MultipartFile file) {
		log.info("upload file start...");
		SysFileVo vo = null;

		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		String url = "";

		//0-共享存储  1-minio
		Integer uploadType = fileUploadConfig.getUploadType();
		Long fileSize = file.getSize();
		if(uploadType == 1){
			url = String.format("/admin/sys-file/%s/%s", CommonConstants.BUCKET_NAME, fileName);

			try {
				minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
				//文件管理数据记录,收集管理追踪文件
				fileLog(file, fileName, fileSize);
			} catch (Exception e) {
				log.error("上传失败", e);
				return R.failed(e.getLocalizedMessage());
			}
		}else{
			url = String.format(fileUploadConfig.getAccessPath() + "/%s", fileName);
			String realPath = fileUploadConfig.getRealPath();

			try{
				File dest = new File(realPath + "/" + fileName);
				file.transferTo(dest);
				fileLog(file, fileName, fileSize);
			}catch (Exception e) {
				log.error("上传失败", e);
				return R.failed(e.getLocalizedMessage());
			}
		}
		log.info("store file finish...");
		//设置返回
		vo = handleFile(file, fileName, url, fileSize);
		return R.ok(vo);
	}

	@Override
	public R uploadFile(MultipartFile file, String name) {
		log.info("upload file start...");
		SysFileVo vo = null;

		String fileName = name;
		String url = "";

		//0-共享存储  1-minio
		Integer uploadType = fileUploadConfig.getUploadType();
		Long fileSize = file.getSize();
		if(uploadType == 1){
			url = String.format("/admin/sys-file/%s/%s", CommonConstants.BUCKET_NAME, fileName);

			try {
				minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
				//文件管理数据记录,收集管理追踪文件
				fileLog(file, fileName, fileSize);
			} catch (Exception e) {
				log.error("上传失败", e);
				return R.failed(e.getLocalizedMessage());
			}
		}else{
			url = String.format(fileUploadConfig.getAccessPath() + "/%s", fileName);
			String realPath = fileUploadConfig.getRealPath();

			try{
				File dest = new File(realPath + "/" + fileName);
				file.transferTo(dest);
				fileLog(file, fileName, fileSize);
			} catch (Exception e) {
				log.error("上传失败", e);
				return R.failed(e.getLocalizedMessage());
			}
		}
		log.info("store file finish...");
		//设置返回
		vo = handleFile(file, fileName, url, fileSize);
		return R.ok(vo);
	}

	/**
	 * 读取文件
	 *
	 * @param bucket
	 * @param fileName
	 * @param response
	 */
	@Override
	public void getFile(String bucket, String fileName, HttpServletResponse response) {
		try (InputStream inputStream = minioTemplate.getObject(bucket, fileName)) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常", e);
		}
	}


	/**
	 * 删除文件
	 *
	 * @param id
	 * @return
	 */
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteFile(Long id) {
		SysFile file = this.getById(id);
		minioTemplate.removeObject(CommonConstants.BUCKET_NAME, file.getFileName());
		return this.removeById(id);
	}

	/**
	 * 文件管理数据记录,收集管理追踪文件
	 *
	 * @param file     上传文件格式
	 * @param fileName 文件名
	 */
	private void fileLog(MultipartFile file, String fileName, Long fileSize) {
		SysFile sysFile = new SysFile();
		//原文件名
		String original = file.getOriginalFilename();
		sysFile.setFileName(fileName);
		sysFile.setOriginal(original);
		sysFile.setFileSize(fileSize);
		sysFile.setType(FileUtil.extName(original));
		sysFile.setBucketName(CommonConstants.BUCKET_NAME);
		MadpUser madpUser = SecurityUtils.getUser();
		sysFile.setCreateUser(madpUser == null ? "" : madpUser.getUsername());
		this.save(sysFile);
	}

	/**
	 * 文件响应信息处理
	 * @param file
	 * @param fileName
	 * @param url
	 * @return
	 */
	private SysFileVo handleFile(MultipartFile file, String fileName, String url, Long fileSize){
		SysFileVo vo = new SysFileVo();
		//原文件名
		String original = file.getOriginalFilename();
		vo.setBucketName(CommonConstants.BUCKET_NAME);
		vo.setFileName(fileName);
		vo.setOriginal(original);
		vo.setFileSize(fileSize);
		vo.setType(FileUtil.extName(original));
		vo.setUrl(url);

		return vo;
	}


}
